package com.klm.easymq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Easy-MQ 配置加载器
 * 用于加载SDK内部的默认配置文件
 * 简化设计：只提供默认配置，环境配置由主应用管理
 */
@Slf4j
@Component
public class ConfigurationLoader {
    
    private static final String DEFAULT_CONFIG_PATH = "application-easymq.yml";
    
    /**
     * 加载默认配置
     * 只加载SDK内部的默认配置文件，不处理环境特定配置
     */
    public Map<String, Object> loadDefaultConfig() {
        Map<String, Object> config = new HashMap<>();
        
        // 只加载默认配置文件
        config.putAll(loadYamlConfig(DEFAULT_CONFIG_PATH));
        
        log.info("加载Easy-MQ SDK默认配置完成");
        return config;
    }
    
    /**
     * 加载YAML配置文件
     */
    private Map<String, Object> loadYamlConfig(String configPath) {
        Map<String, Object> config = new HashMap<>();
        
        try {
            Resource resource = new ClassPathResource(configPath);
            if (resource.exists()) {
                try (InputStream inputStream = resource.getInputStream()) {
                    Yaml yaml = new Yaml();
                    Object obj = yaml.load(inputStream);
                    if (obj instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> yamlConfig = (Map<String, Object>) obj;
                        config.putAll(yamlConfig);
                        log.debug("成功加载配置文件: {}", configPath);
                    }
                }
            } else {
                log.debug("配置文件不存在: {}", configPath);
            }
        } catch (IOException e) {
            log.warn("加载配置文件失败: {}, 错误: {}", configPath, e.getMessage());
        }
        
        return config;
    }
    
    /**
     * 绑定配置到属性对象
     */
    public <T> T bindConfig(Map<String, Object> config, String prefix, Class<T> targetClass) {
        try {
            ConfigurationPropertySource source = new MapConfigurationPropertySource(config);
            Binder binder = new Binder(source);
            return binder.bind(prefix, Bindable.of(targetClass)).orElse(null);
        } catch (Exception e) {
            log.warn("绑定配置失败: {}, 错误: {}", prefix, e.getMessage());
            return null;
        }
    }
} 